

package com.coding4play.mqtt.broker.server;

import cn.hutool.extra.spring.SpringUtil;
import com.coding4play.mqtt.broker.codec.MqttWebSocketCodec;
import com.coding4play.mqtt.broker.config.BrokerProperties;
import com.coding4play.mqtt.broker.handler.BrokerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLEngine;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * 启动Broker
 */
@Component
@Slf4j
public class BrokerServer implements SmartInitializingSingleton {
    private BrokerProperties brokerProperties;
    private SslContext sslContext;

    public BrokerServer(BrokerProperties brokerProperties) {
        this.brokerProperties = brokerProperties;
    }

    @PostConstruct
    public void postConstruct() throws Exception {
        if (brokerProperties.getSslEnabled()) {
            KeyStore keyStore = KeyStore.getInstance("PKCS12");
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("keystore/server.pfx");
            keyStore.load(inputStream, brokerProperties.getSslPassword().toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(keyStore, brokerProperties.getSslPassword().toCharArray());
            sslContext = SslContextBuilder.forServer(kmf).build();
        }
    }

    @Override
    public void afterSingletonsInstantiated() {
        log.info("Initializing [{}] MQTT Broker ...", brokerProperties.getId());

        Integer bossGroupThreads = brokerProperties.getBossGroupThreads();
        Integer workerGroupThreads = brokerProperties.getWorkerGroupThreads();
        Boolean useEpoll = brokerProperties.getUseEpoll();
        EventLoopGroup bossGroup = useEpoll ? new EpollEventLoopGroup(bossGroupThreads) : new NioEventLoopGroup(bossGroupThreads);
        EventLoopGroup workerGroup = useEpoll ? new EpollEventLoopGroup(workerGroupThreads) : new NioEventLoopGroup(workerGroupThreads);
        Class<? extends ServerSocketChannel> channelClazz = useEpoll ? EpollServerSocketChannel.class : NioServerSocketChannel.class;

        mqttServer(bossGroup, workerGroup, channelClazz);
        websocketServer(bossGroup, workerGroup, channelClazz);
    }


    private void mqttServer(EventLoopGroup bossGroup, EventLoopGroup workerGroup, Class<? extends ServerSocketChannel> socketChannelClazz) {
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup)
                .channel(socketChannelClazz)
                .option(ChannelOption.SO_BACKLOG, brokerProperties.getSoBacklog())
                .childOption(ChannelOption.SO_KEEPALIVE, brokerProperties.getSoKeepAlive())
                // handler在初始化时就会执行
                .handler(new LoggingHandler(LogLevel.INFO))
                // childHandler会在客户端成功connect后才执行
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline channelPipeline = socketChannel.pipeline();
                        // Netty提供的心跳检测
                        channelPipeline.addFirst("idle", new IdleStateHandler(0, 0, brokerProperties.getKeepAlive()));
                        // Netty提供的SSL处理
                        addSsl(channelPipeline, socketChannel);
                        channelPipeline.addLast("decoder", new MqttDecoder());
                        channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                        channelPipeline.addLast("broker", SpringUtil.getBean(BrokerHandler.class));
                    }
                });

        try {
            sb.bind(brokerProperties.getHost(), brokerProperties.getPort()).sync();
            log.info("MQTT Broker [{}] running in port: {} ", brokerProperties.getId(), brokerProperties.getPort());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void websocketServer(EventLoopGroup bossGroup, EventLoopGroup workerGroup, Class<? extends ServerSocketChannel> socketChannelClazz) {
        if (!this.brokerProperties.getWebsocket().getEnable()) {
            return;
        }
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(bossGroup, workerGroup)
                .channel(socketChannelClazz)
                .option(ChannelOption.SO_BACKLOG, brokerProperties.getSoBacklog())
                .childOption(ChannelOption.SO_KEEPALIVE, brokerProperties.getSoKeepAlive())
                // handler在初始化时就会执行
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline channelPipeline = socketChannel.pipeline();
                        // Netty提供的心跳检测
                        channelPipeline.addFirst("idle", new IdleStateHandler(0, 0, brokerProperties.getKeepAlive()));
                        // Netty提供的SSL处理
                        addSsl(channelPipeline, socketChannel);
                        // 将请求和应答消息编码或解码为HTTP消息
                        channelPipeline.addLast("http-codec", new HttpServerCodec());
                        // 将HTTP消息的多个部分合成一条完整的HTTP消息
                        channelPipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
                        // 将HTTP消息进行压缩编码
                        channelPipeline.addLast("compressor ", new HttpContentCompressor());
                        channelPipeline.addLast("protocol", new WebSocketServerProtocolHandler(brokerProperties.getWebsocket().getPath(), "mqtt,mqttv3.1,mqttv3.1.1", true, 65536));
                        channelPipeline.addLast("mqttWebSocket", new MqttWebSocketCodec());
                        channelPipeline.addLast("decoder", new MqttDecoder());
                        channelPipeline.addLast("encoder", MqttEncoder.INSTANCE);
                        channelPipeline.addLast("broker", SpringUtil.getBean(BrokerHandler.class));
                    }
                });

        try {
            sb.bind(brokerProperties.getHost(), brokerProperties.getWebsocket().getPort()).sync();
            log.info("MQTT Broker WebSocket running in port: {}, path: {}", brokerProperties.getWebsocket().getPort(), brokerProperties.getWebsocket().getPath());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * socket add ssl
     * @param channelPipeline
     * @param socketChannel
     */
    public void addSsl(ChannelPipeline channelPipeline, SocketChannel socketChannel) {
        if (this.brokerProperties.getSslEnabled()) {
            SSLEngine sslEngine = sslContext.newEngine(socketChannel.alloc());
            sslEngine.setUseClientMode(false);        // 服务端模式
            sslEngine.setNeedClientAuth(false);        // 不需要验证客户端
            channelPipeline.addLast("ssl", new SslHandler(sslEngine));
        }
    }

}
